package com.cw.jeeyt.controller.api;

import java.util.ArrayList;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cw.jeeyt.api.dto.response.JsonResultDto;
import com.cw.jeeyt.common.DataTable;
import com.cw.jeeyt.common.ResultData;
import com.cw.jeeyt.common.enums.EnumOperateFlag;
import com.cw.jeeyt.common.web.BaseController;
import com.cw.jeeyt.service.bo.api.ApiDataEntryBo;
import com.cw.jeeyt.service.intf.api.ApiDataEntryService;
import com.cw.jeeyt.service.directive.PageDictDirective;
import com.cw.jeeyt.service.directive.PermissionDirective;
import com.cw.lang.common.utils.CollectionUtil;
import com.cw.lang.mybatis.dto.PageInfo;

/**
 * 接口字段信息控制层
 *
  * @author chenw
 * @version 1.0.0
 */
@Controller
@RequestMapping("/apiDataEntry")
public class ApiDataEntryController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(ApiDataEntryController.class);
    @Resource
    private ApiDataEntryService apiDataEntryService;

    /**
     * 跳转到接口字段信息列表查询页面
     *
     * @param apiDataEntryBo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/query")
    public ModelAndView query() throws Exception {

        ModelAndView mv = new ModelAndView("api/apiDataEntry_index");
        mv.addObject("permission", new PermissionDirective());
        mv.addObject("PageDict", new PageDictDirective());
        return mv;
    }

    /**
     * 加载DataTable列表数据
     *
     * @param dataTable 请求数据
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/listApiDataEntry")
    public ResultData listApiDataEntry(@RequestBody DataTable dataTable) throws Exception {

        ApiDataEntryBo apiDataEntryBo = JSONObject.parseObject(JSON.toJSONString(dataTable.getQueryCond()),
            ApiDataEntryBo.class);
        if (apiDataEntryBo == null) {
            apiDataEntryBo = new ApiDataEntryBo();
        }
        PageInfo<ApiDataEntryBo> pageInfo = apiDataEntryService.queryByPage(apiDataEntryBo, dataTable.getStart(),
            dataTable.getLength(), dataTable.getOrder()[0]);
        return ResultData.builder()
            .draw(dataTable.getDraw())
            .data(CollectionUtil.isNotEmpty(pageInfo.getList())?pageInfo.getList():new ArrayList())
            .recordsTotal(pageInfo.getTotal())
            .recordsFiltered(pageInfo.getTotal())
            .build();
    }

    /**
     * 跳转到导入数据条目
     *
     * @return
     */
    @RequestMapping(value = "/to-importDataEntry")
    public ModelAndView toImport(String selectType, Long objId) {
        ModelAndView mv = new ModelAndView("api/apiDataEntry_importIndex");
        mv.addObject("permission", new PermissionDirective());
        mv.addObject("selectType", selectType);
        mv.addObject("objId", objId);
        return mv;
    }

    /**
     * 加载DataTable列表数据
     *
     * @param dataTable 请求数据
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/listImportApiDataEntry")
    public ResultData listImportApiDataEntry(@RequestBody DataTable dataTable, Long objId) throws Exception {

        ApiDataEntryBo apiDataEntryBo = JSONObject.parseObject(JSON.toJSONString(dataTable.getQueryCond()),
            ApiDataEntryBo.class);
        if (apiDataEntryBo == null) {
            apiDataEntryBo = new ApiDataEntryBo();
        }
        PageInfo<ApiDataEntryBo> pageInfo = apiDataEntryService.queryImortByPage(apiDataEntryBo, dataTable.getStart(),
            dataTable.getLength(), dataTable.getOrder()[0], objId);
        return ResultData.builder()
            .draw(dataTable.getDraw())
            .data(CollectionUtil.isNotEmpty(pageInfo.getList())?pageInfo.getList():new ArrayList())
            .recordsTotal(pageInfo.getTotal())
            .recordsFiltered(pageInfo.getTotal())
            .build();
    }

    /**
     * 跳转到接口字段信息表单页面
     *
     * @param operation 操作  add 新增 edit修改 view查看
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/to-form")
    public ModelAndView editForm(Long id, String operation) throws Exception {

        ModelAndView mv = new ModelAndView("api/apiDataEntry_form");
        ApiDataEntryBo apiDataEntryBo = null;
        if (EnumOperateFlag.ADD.getCode()
            .equals(operation)) {
            apiDataEntryBo = new ApiDataEntryBo();
        } else {
            apiDataEntryBo = apiDataEntryService.getApiDataEntryById(id);
        }
        mv.addObject("apiDataEntry", apiDataEntryBo);
        mv.addObject("operation", operation);
        mv.addObject("PageDict", new PageDictDirective());
        mv.addObject("permission", new PermissionDirective());
        return mv;
    }

    /**
     * 根据操作类型保存接口字段信息数据
     *
     * @param apiDataEntryBo
     * @param operation add 新增  edit 修改
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/saveApiDataEntry", method = RequestMethod.POST)
    public JsonResultDto saveApiDataEntry(ApiDataEntryBo apiDataEntryBo, String operation) {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            if (operation.equals(EnumOperateFlag.ADD.getCode())) {
                apiDataEntryService.insert(apiDataEntryBo);
            } else if (operation.equals(EnumOperateFlag.EDIT.getCode())) {
                apiDataEntryService.update(apiDataEntryBo);
            }
            jsonResultDto.setMsg("保存成功");
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            jsonResultDto.setMsg("保存失败:" + e.getMessage());
            e.printStackTrace();
            logger.error("保存接口字段信息失败：" + e.getMessage());
        }
        return jsonResultDto;
    }

    /**
     * 删除接口字段信息
     *
     * @param apiDataEntryBo
     * @throws Exception
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public JsonResultDto delete(ApiDataEntryBo apiDataEntryBo)
    throws Exception {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            apiDataEntryService.delete(apiDataEntryBo);
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();

            jsonResultDto.setMsg("删除失败：" + e.getMessage());
            logger.error("删除接口字段信息失败：" + e.getMessage());
        }
        return jsonResultDto;
    }

    /**
     * 同步接口字段信息
     *
     * @param databaseId
     */
    @RequestMapping(value = "/syncDataEntry")
    @ResponseBody
    public JsonResultDto syncDataEntry(String databaseId) {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            apiDataEntryService.syncDataEntry(databaseId);
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResultDto.setMsg("同步接口字段信息失败：" + e.getMessage());
            logger.error("同步接口字段信息失败：" + e.getMessage());
        }
        return jsonResultDto;
    }
}
